<?php

class UserController extends Controller
{
	public $layout='//layouts/column1';
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xF5F5F5,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		//	'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('register','captcha' , 'contact', 'view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update', 'changepass', 'logout', 'profile','SuggestPerson', 'dangkyvip','historylogin'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete','management', 'setstate', 'resetpassword', 'logout'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	//hien tai search khong phan trang, ben DAO cho page size max 99999 de chi hien thi trong 1 trang
	// luc nay se search live tot
	public function actionSuggestPerson() {
		$criteria = new CDbCriteria;
		$criteria->select = array('id', 'username');
	
		$criteria->addSearchCondition('username',  strtoupper( $_POST['term']) ) ;
		$criteria->limit = 15;
		$data = User::model()->findAll($criteria);
	
		$arr = array();
	
		foreach ($data as $item) {
			 
			$arr[] = array(
					'id'=>$item->id,
					'username' => $item->username,
					'hoten' => $item->hoten,
					'email' => $item->email,
					'dienthoai' => $item->dienthoai,
					'trangthai' => $item->trangthai
					
			);
		}
	
		echo CJSON::encode($arr);
	
	}
	
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionRegister()
	{
		$model=new User;
		if(isset($_POST['User']))
		{
			$model->attributes=$_POST['User'];
			$model->ngaysinh = DateUtils::ConvertDateTimeformat($model->ngaysinh);
			if($model->validate()){
				if(Userdao::Register( $model))
					Yii::app()->user->setFlash('success', 'Đăng ký tài khoản thành công !.');
			}
			$model->password ='';
			$model->confirm ='';
		}

		$this->render('register',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
		if(isset($_POST['User']))
		{
			$model->attributes=$_POST['User'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{//xoa mua dich vu
		$criteria = new CDbCriteria();
		$criteria->compare('iduser', $id);
		$val = Muadichvu::model()->findAll($criteria);
		if($val != null){
			foreach($val as $item){
				$item->delete();
			}
		}
		//xoa gia dichvuuser
		$criteria = new CDbCriteria();
		$criteria->compare('iduser', $id);
		$val = GiadichvuUser::model()->findAll($criteria);
		if($val != null){
			foreach($val as $item){
				$item->delete();
			}
		}
		//xoa credit
		$cre = Credit::model()->findByAttributes(array('iduser'=>$id));
		if($cre != null){
			foreach($cre->tbchitietnapcredits as $item){
				$item->delete();
			}
			$cre->delete();
		}

		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('User');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new User('search');
		$model->unsetAttributes();  
		if(isset($_GET['User']))
			$model->attributes=$_GET['User'];
		$data['model']=$model;
		$this->render('admin',$data);
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=User::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	public function actionManagement(){
		$this->render('management');
	}
	
	public function actionChangePass(){
		$model= new UserForm;
		if(isset($_POST['UserForm']))
		{
			$model->attributes=$_POST['UserForm'];
			if(strlen($model->password) >= 6){
				if(Userdao::changepass( $model )){
					$model->unsetAttributes();
					Yii::app()->user->setFlash('success', 'Thay đổi mật khẩu thành công !.');
				}else{
					Yii::app()->user->setFlash('error', 'Thay đổi mật khẩu khồn thành công, vui lòng kiểm tra lại thông tin !.');
				}
			}else{
				Yii::app()->user->setFlash('error', 'Mật khẩu ít nhất 6 ký tự !.');
			}
		}

		$this->render('changepass',array(
			'model'=>$model,
		));
	}
	
/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(array(Yii::app()->homeUrl));
	}
	
	public function actionProfile(){
		$model= Yii::app()->user->getId();
		$model->ngaysinh ='';
		if(isset($_POST['User']))
		{
			$model->attributes=$_POST['User'];
			$model->ngaysinh = DateUtils::ConvertDateTimeformat($model->ngaysinh);
			if(Userdao::updateProfile($model)){
				Yii::app()->user->setFlash('success', 'Thay đổi thông tin tài khoản thành công !.');
			}
		}
		$this->render('profile',array('model'=>$model));
	}
	
	public function actionSetState($id, $trangthai){
		$model=User::model()->findByPk($id);
		$model->trangthai = $trangthai;
		$model->update();
		$this->redirect(array('admin'));
	}
	
	public function actionResetpassword($id){
		$model=User::model()->findByPk($id);
		Userdao::resetPassword($model);
		$this->redirect(array('admin'));
	}
	
/**
	 * Displays the contact page
	 */
	public function actionContact()
	{
		$model=new ContactForm;
		if(!Yii::app()->user->isGuest){
			$model->email = Yii::app()->user->getId()->email;
			$model->name = Yii::app()->user->getId()->hoten;
			if(!isset($model->name)){
				$model->email = Yii::app()->user->getId()->username;
			}
		}
		if(isset($_POST['ContactForm']))
		{
			$model->attributes=$_POST['ContactForm'];
			if($model->validate())
			{
				$name='=?UTF-8?B?'.base64_encode($model->name).'?=';
				$headers="From: $name <{$model->email}>\r\n".
					"Reply-To: {$model->email}\r\n".
					"MIME-Version: 1.0\r\n".
					"Content-type: text/plain; charset=UTF-8";
				$model->body = "<p>From: ". $model->name. " </p><p> Email: ". $model->email. " </p> ".$model->body;
				EmailUtils::contact('Liên hệ GSM-SERVER.NET',$model->body,$headers);
				Yii::app()->user->setFlash('success','Cám ơn quý khách đã liên hệ với chúng tôi, chúng tôi sẻ trả lời quý khách sớm nhất.');
			//	$this->refresh();
			}
		}
		$this->render('contact',array('model'=>$model));
	}
	
	public function actionDangKyVip(){
		$model=new VipForm;
		if(isset($_POST['VipForm'])){
			$body = '';
			$model->attributes=$_POST['VipForm'];
			if($model->validate()){
				$body = '';
				foreach ($model->attributes as $key => $value){
					$body = $body. '<p>'. $key. ': <b>'. $value. '</b></p><br/>';
				}
				EmailUtils::sendmail('vinh_unlockcellphone@yahoo.com', 'Thông tin đăng ký VIP '. $model->username, $body, '');
				Yii::app()->user->setFlash('dangkyvip','Cám ơn quý khách đã sử dụng dịch vụ của chúng tôi, yêu cầu của quý khách đang được xử lý.');
				$this->refresh();
			}
		}
		$this->render('dangkyvip',array('model'=>$model));
	}
	
	public function actionHistoryLogin(){
		$model=new Tblog('search');
		if(isset($_REQUEST['Tblog'])){
			$model->attributes = $_REQUEST['Tblog'];
		}
		$model->username = Yii::app()->user->getId()->username;
		$this->render('historylogin', array('model'=>$model));
	}
}
